package com.example.lin.service.impl;

import com.example.lin.entity.dto.LoginDto;
import com.example.lin.entity.vo.LoginUser;
import com.example.lin.exception.GlobalException;
import com.example.lin.service.LoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 登录
     * @param loginDto 用户名、密码
     * @return loginUser
     */
    @Override
    public LoginUser login(LoginDto loginDto) {
        log.info("login：[{}]", loginDto);
        try {
//            String password = bCryptPasswordEncoder.encode(loginDto.getPassword());
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
            Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            if (ObjectUtils.isEmpty(authenticate)) {
                log.warn("用户不存在");
                throw new GlobalException("用户名或密码错误");
            }
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(() -> "sys:user:list");
            authorities.add(() -> "sys:user:save");
            loginUser.getUser().setAuthorities(authorities);
            return loginUser;
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                log.error("用户名或密码错误");
                throw new GlobalException("用户名或密码错误");
            } else {
                log.error(e.getMessage());
                throw new GlobalException("登录失败");
            }
        }
    }
}
